<template>
  <el-drawer
    v-loading="drawerLoading"
    :visible.sync="dialogVisible"
    append-to-body
    show-close
    :title="info.name"
    :direction="direction"
    size="70%"
    style="min-width: 1036px"
    :before-close="handleClose"
  >
    <div class="app-container">
      <div class="header">
        <el-row :gutter="20" style="padding: 30px 20px 5px">
          <el-col :span="14">
            <div style="display: flex">
              <div style="margin-right: 15px">
                <img
                  src=""
                  class="t-section__hd"
                />
              </div>
              <div style="line-height: 1.15">
                <span class="customer-title">{{
                  $t('customer.customer')
                }}</span>
                <br />
                <span class="customer-name">{{ info.name }}</span>

                <span class="customer-name">
                  <el-rate
                    v-model="info.attention"
                    :disabled="isWater"
                    @change="setCustomerAttention(info.id, info.attention)"
                    :colors="colors"
                  >
                  </el-rate>
                </span>
              </div>
            </div>
          </el-col>
          <el-col :span="10">
            <div style="line-height: 2">
              <template v-if="isMy || isIntention">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editRow()"
                  >{{ $t('common.edit') }}</el-button
                >
                <el-button
                  type="success"
                  size="mini"
                  icon="el-icon-success"
                  @click="changeStatusRow()"
                  >{{ $t('customer.updateDealState') }}</el-button
                >
                <el-dropdown style="margin-left: 10px" @command="handleCommand">
                  <el-button size="mini" icon="el-icon-more" />
                  <el-dropdown-menu slot="dropdown">
                    <template v-if="isMy || isIntention">
                      <el-dropdown-item
                        :command="beforeHandleCommand(info.id, 'group')"
                        >{{ $t('customer.setGroup') }}</el-dropdown-item
                      >
                      <el-dropdown-item
                        :command="beforeHandleCommand(info.id, 'label')"
                        >{{ $t('customer.setupTag') }}</el-dropdown-item
                      >
                      <el-dropdown-item
                        :command="beforeHandleCommand(info.id, 'intention')"
                        >{{
                          $t('customer.updateIntentState')
                        }}</el-dropdown-item
                      >
                      <el-dropdown-item
                        :command="beforeHandleCommand(info.id, 'intention')"
                        >{{
                          $t('customer.updateIntentState')
                        }}</el-dropdown-item
                      >
                      <el-dropdown-item
                        :command="
                          beforeHandleCommand(
                            info.id,
                            'email',
                            info.name,
                            info.email
                          )
                        "
                        >{{ $t('customer.newMarketingTask') }}</el-dropdown-item
                      >
                      <el-dropdown-item
                        :command="beforeHandleCommand(info.id, 'private', 0)"
                        >{{ $t('customer.moveToPublic') }}</el-dropdown-item
                      >
                    </template>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
              <template v-if="isWater">
                <el-button
                  size="mini"
                  icon="el-icon-s-fold"
                  @click="privateRow(info.id, 1)"
                  >{{ $t('customer.claimCustomer') }}</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteCustomer(info.id)"
                  >{{ $t('customer.deleteCustomer') }}</el-button
                >
              </template>
            </div>
          </el-col>
        </el-row>
        <el-row style="padding: 8px 20px 15px" :gutter="20" class="head-form">
          <el-form class="demo-form-inline" label-position="top">
            <el-col :span="8">
              <el-form-item :label="$t('customer.dealState')">
                <template v-if="info.dealStatus == 1">
                  <i class="el-icon-success" style="color: #20b559"></i
                  >{{ $t('customer.dealed') }}
                </template>
                <template v-else>
                  <i class="el-icon-error" style="color: #f95a5a"></i
                  >{{ $t('customer.notDeal') }}
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('customer.principal')">
                {{
                  info.belongUser
                    ? info.belongUser.trueName
                    : $t('customer.empty')
                }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('common.updateTime')">
                {{ info.updatedAt }}
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </div>

      <div class="content">
        <el-tabs
          type="border-card"
          v-model="activeName"
          @tab-click="handleTabClick"
        >
          <el-tab-pane :label="$t('customer.detailInfo')" name="info">
            <el-scrollbar
              ref="myScrollbar"
              :wrap-class="{ wrapClass: true }"
              class="form-scrollbar scrollbar-back-top"
            >
              <Info :row="info" v-if="infoTemplateState" :is="infoTemplate" />
            </el-scrollbar>
          </el-tab-pane>
          <el-tab-pane :label="$t('customer.followUpLog')" name="follow">
            <FollowTemplate
              :customerId="id"
              :isShowAction="isMy || isIntention"
              v-if="followTemplateState"
              :is="followTemplate"
              @refresh="getInfo()"
            />
          </el-tab-pane>
          <el-tab-pane :label="$t('customer.operationRecord')" name="log">
            <el-scrollbar
              ref="myScrollbar"
              :wrap-class="{ wrapClass: true }"
              class="form-scrollbar scrollbar-back-top"
            >
              <Log :id="id" v-if="logTemplateState" :is="logTemplate" />
            </el-scrollbar>
          </el-tab-pane>
          <template v-if="isMy || isIntention">
            <el-tab-pane :label="$t('route.emailMarketingTask')" name="email">
              <el-scrollbar
                ref="myScrollbar"
                :wrap-class="{ wrapClass: true }"
                class="form-scrollbar scrollbar-back-top"
              >
                <EmailMarketingTaskIndex
                  :ids="emailIds"
                  v-if="emailMarketingTaskIndexState"
                  :is="emailMarketingTaskIndex"
                />
              </el-scrollbar>
            </el-tab-pane>
          </template>
        </el-tabs>
      </div>
    </div>
    <Edit :id="id" :show.sync="showState" @closeAction="getInfo" :origin="1" />
    <ChangeDealStatus
      :id="id"
      :show.sync="showChangeDealStatusState"
      @closeAction="getInfo"
    />
    <Group :id="id" :show.sync="showGroupState" @closeAction="getInfo" />
    <Intention
      :id="id"
      :show.sync="showIntentionState"
      @closeAction="getInfo"
    />
    <Label :id="id" :show.sync="showLabelState" @closeAction="getInfo" />
    <EmailAdd
      :emailsTemp="emailData"
      :show.sync="showBaseFormState"
      @closeAction="getInfo"
    />
  </el-drawer>
</template>

<script>
const Log = (resolve) => require(['@/views/customer/common/log'], resolve)
const Info = (resolve) => require(['@/views/customer/common/info'], resolve)
const FollowTemplate = (resolve) =>
  require(['@/views/customer/common/follow'], resolve)
const EmailMarketingTaskIndex = (resolve) =>
  require(['@/views/email/emailMarketingTask/index'], resolve)
import ChangeDealStatus from '@/views/customer/common/changeDealStatus'
import Group from '@/views/customer/common/group'
import Label from '@/views/customer/common/label'
import Intention from '@/views/customer/common/intention'
import Edit from './edit'
import {
  deleteCustomer,
  getCustomer,
  setAttention,
  SetIsPrivate,
} from '@/api/customer'
import EmailAdd from '@/views/customer/index/emailAdd'

export default {
  name: 'Drawer',
  components: {
    Info,
    Log,
    Edit,
    ChangeDealStatus,
    Group,
    Label,
    Intention,
    EmailAdd,
  },
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [Number, String],
      default: '',
    },
    closeAction: {
      type: String,
      default: '',
    },
    action: {
      type: [Number, String],
      default: '',
    },
  },
  created() {
    this.initAction()
  },
  data() {
    return {
      isMy: false,
      isIntention: false,
      isWater: false,
      emailIds: [],
      emailData: [],
      showBaseFormState: false,
      dialogVisible: this.show,
      showState: false,
      showIntentionState: false,
      showGroupState: false,
      showLabelState: false,
      showChangeDealStatusState: false,
      direction: 'rtl',
      colors: ['#99A9BF', '#F7BA2A', '#FF9900'],
      attention: 5,
      drawerLoading: true,
      info: {
        name: '',
        attention: 0,
        dealStatus: 0,
      },
      activeName: 'info',
      infoTemplate: '',
      infoTemplateState: false,
      logTemplate: '',
      logTemplateState: false,
      followTemplate: '',
      followTemplateState: false,
      emailMarketingTaskIndex: '',
      emailMarketingTaskIndexState: false,
    }
  },
  methods: {
    initAction() {
      //初始化
      this.isMy = false
      this.isIntention = false
      this.isWater = false

      if (this.action == 1) {
        this.isMy = true
      } //我的客户
      if (this.action == 2) {
        this.isIntention = true
      } //意向客户
      if (this.action == 3) {
        this.isWater = true
      } //
    },
    async getInfo() {
      this.showState = false
      this.showChangeDealStatusState = false
      this.showIntentionState = false
      this.showGroupState = false
      this.showLabelState = false
      this.drawerLoading = true
      await getCustomer(this.id)
        .then((res) => {
          this.info = res.data
          setTimeout(() => {
            this.drawerLoading = false
          }, 0.5 * 1000)
        })
        .catch(() => {
          setTimeout(() => {
            this.drawerLoading = false
          }, 0.5 * 1000)
        })
    },
    handleClose(done) {
      this.$emit('closeAction')
    },
    setCustomerAttention(id, val) {
      this.$confirm(
        this.$t('customer.confirmUpdateCustomerAttention'),
        this.$t('common.tips'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning',
        }
      )
        .then(async () => {
          this.drawerLoading = true
          let data = { id: id, attention: val }
          await setAttention(data).then((res) => {
            this.$notify({
              title: this.$t('common.success'),
              message: this.$t('common.updateSuccessfully'),
              type: 'success',
              duration: 2000,
            })
            this.getInfo()
          })
        })
        .catch(() => {
          this.getInfo()
        })
    },
    editRow() {
      this.showState = true
    },
    changeStatusRow() {
      this.showChangeDealStatusState = true
    },
    checkTab(name) {
      switch (name) {
        case 'info':
          this.infoTemplateState = false
          this.infoTemplate = Info
          this.$nextTick(() => {
            this.infoTemplateState = true
          })
          break
        case 'log':
          this.logTemplateState = false
          this.logTemplate = Log
          this.$nextTick(() => {
            this.logTemplateState = true
          })
          break
        case 'follow':
          this.followTemplateState = false
          this.followTemplate = FollowTemplate
          this.$nextTick(() => {
            this.followTemplateState = true
          })
          break
        case 'email':
          this.emailIds = []
          this.emailIds.push(this.info.id)
          this.emailMarketingTaskIndexState = false
          this.emailMarketingTaskIndex = EmailMarketingTaskIndex
          this.$nextTick(() => {
            this.emailMarketingTaskIndexState = true
          })
          break
      }
    },
    handleTabClick(tab, event) {
      this.checkTab(tab.name)
    },
    beforeHandleCommand(scope, command, val1 = 0, val2 = null) {
      return {
        scope: scope,
        command: command,
        val: val1,
        val2: val2,
      }
    },
    handleCommand(command) {
      switch (command.command) {
        case 'group':
          this.groupRow(command.scope)
          break
        case 'label':
          this.labelRow(command.scope)
          break
        case 'intention':
          this.intentionRow(command.scope)
          break
        case 'private':
          this.privateRow(command.scope, command.val)
          break
        case 'email':
          this.emailData = []
          let data = {
            id: command.scope,
            name: command.val,
            email: command.val2,
          }
          this.emailData.push(data)
          this.showBaseFormState = true
          break
      }
    },
    groupRow(id) {
      this.showGroupState = true
    },
    labelRow(id) {
      this.showLabelState = true
    },
    intentionRow(id) {
      this.showIntentionState = true
    },
    privateRow(id, val) {
      this.setCustomerIsPrivateRes(val)
    },
    setCustomerIsPrivateRes(val = 0) {
      let msg = ''
      let title = ''
      if (val == 0) {
        title = this.$t('customer.moveTo')
        msg = this.$t('customer.confirmMoveToPublic')
        if (typeof this.id != 'object') {
          msg = this.$t('customer.confirmMoveCustomerToPublic')
        }
      } else {
        title = this.$t('customer.claim')
        msg = this.$t('customer.confirmClaimCurrentCustomer')
        if (typeof this.id != 'object') {
          msg = this.$t('customer.confirmClaimCustomer')
        }
      }

      this.$confirm(msg, this.$t('common.tips'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning',
      }).then(async () => {
        let data = { ids: this.id, value: val }

        if (typeof data.ids != 'object') {
          data.ids = [data.ids]
        }
        await SetIsPrivate(data).then((res) => {
          this.$notify({
            title: this.$t('common.success'),
            message: `${title}${this.$t('common.success')}`,
            type: 'success',
            duration: 2000,
          })
          this.$emit('closeAction')
        })
      })
    },
    deleteCustomer(id) {
      this.$confirm(
        this.$t('customer.confirmDeleteCustomer'),
        this.$t('common.tips'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning',
        }
      )
        .then(async () => {
          await deleteCustomer(id).then((res) => {
            this.$notify({
              title: this.$t('common.success'),
              message: this.$t('common.deleteSuccessfully'),
              type: 'success',
              duration: 2000,
            })
            this.$emit('closeAction')
          })
        })
        .catch(() => {})
    },
  },
  watch: {
    show() {
      this.dialogVisible = this.show
      if (this.show) {
        this.getInfo()
        this.activeName = 'info'
        this.checkTab(this.activeName)
      }
    },
  },
}
</script>

<style scoped>
.head-form /deep/ .el-form-item__label {
  height: 20px;
  font-size: 12px;
  color: #666;
}

.head-form /deep/ .el-form-item {
  margin-bottom: unset;
}

.customer-title {
  color: #999;
  font-size: 12px;
  margin-bottom: 5px;
}

.customer-name {
  color: #333;
  font-size: 16px;
  font-weight: 600;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.header {
  position: relative;
  background-color: #fff;
  border-bottom: 1px solid #e6e6e6;
  margin-bottom: 10px;
}

.form-scrollbar {
  height: calc(100vh - 325px);
}

.form-scrollbar /deep/ .el-timeline {
  margin: 15px 0 0 0;
}
/deep/ .el-drawer__header {
  margin-bottom: unset !important;
}
</style>
